<?php

namespace app\index\controller;

use app\common\model\User;
use think\Controller;

class UserController extends Controller {

    public function login(){
        $username = trim(input('post.username'));
        $password = trim(input('post.password'));

        if( $username == '' || $password == '' ){
            return json(array('type'=>1,'msg'=>'用户名或密码必须填写'));
        }

        $userModel = new User();
        $result = $userModel -> getUserDataByUsername($username);
        if(count($result)<1){
            return json(array('type'=>1,'msg'=>'用户名或密码错误'));
            
        }
        $userData = $result[0];
        if($userData['password'] != $password){
            return json(array('type'=>1,'msg'=>'密码错误'));
        }else{
            cookie('userData',['uid'=>$userData['uid'],'username'=>$userData['username']],7*24*60*60);
            return json(array('type'=>0,'msg'=>'登陆成功'));
        }
    }

    public function register(){
        $username = trim(input('post.username'));
        $password = trim(input('post.password'));
        $repassword = trim(input('post.repassword'));

        if($username == '' || $password == '' || $repassword == '' ){
            return json(array('type'=>1,'msg'=>'用户名、密码和确认密码必须填写'));
        }

        if(mb_strlen($username)>20){
            return json(array('type'=>1,'msg'=>'用户名长度不能超过20个字符'));
        }
        if(strlen($password)>20){
            return json(array('type'=>1,'msg'=>'密码长度不能超过20个字符'));
        }
        if($password != $repassword){
            return json(array('type'=>1,'msg'=>'确认密码和密码不一致'));
        }

        $userModel = new User();
        $result = $userModel -> getUserDataByUsername($username);
        if(count($result)>0){
            return json(array('type'=>1,'msg'=>'该用户名已被注册'));
        }

        $userModel -> add($username,$password);
        $uid = $userModel->getUserDataByUsername($username)[0]['uid'];
        cookie('userData',['uid'=>$uid,'username'=>$username],7*24*60*60);

        return json(array('type'=>0,'msg'=>'注册成功'));

    }

    public function loginout(){
        cookie('userData',null);
        $this -> success('退出成功，返回首页','/');
    }

}